package com.jichangxiu.common.entity.bo;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jichangxiu.common.utils.SqlUtils;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

@Data
public class PageEntity implements Serializable {

    private static final long serialVersionUID = 1L;

    // 当前记录起始索引 默认值
    public static final Long DEFAULT_PAGE_NUM = 1L;

    // 每页显示记录数 默认值 默认查全部
    public static final Long DEFAULT_PAGE_SIZE = Long.MAX_VALUE;

    // 分页大小
    private Long pageSize;

    // 当前页数
    private Long pageNum;

    // 排序列
    private String orderBy;

    // 是否为 ASC
    private Boolean isAsc;

    public <T> Page<T> build() {
        Long pageNum = ObjectUtil.defaultIfNull(getPageNum(), DEFAULT_PAGE_NUM) > 0 ? ObjectUtil.defaultIfNull(getPageNum(), DEFAULT_PAGE_NUM) : DEFAULT_PAGE_NUM;
        Long pageSize = ObjectUtil.defaultIfNull(getPageSize(), DEFAULT_PAGE_SIZE);
        Page<T> page = new Page<>(pageNum, pageSize);
        List<OrderItem> orderItems = buildOrderItem();
        if (CollUtil.isNotEmpty(orderItems)) page.addOrder(orderItems);
        return page;
    }

    private List<OrderItem> buildOrderItem() {
        if (StrUtil.isBlank(getOrderBy()) || ObjectUtil.isEmpty(getIsAsc())) return null;
        String orderBy = StrUtil.toUnderlineCase(SqlUtils.escapeOrderBySql(getOrderBy()));
        // 兼容前端排序类型
        String method = StringUtils.replaceEach(getIsAsc() ? "asc" : "desc", new String[]{"ascending", "descending"}, new String[]{"asc", "desc"});
        String[] orderByArr = orderBy.split(",");
        String[] isAscArr = method.split(",");
        if (isAscArr.length != 1 && isAscArr.length != orderByArr.length)
            throw new RuntimeException("【PageEntity】初始化请求分页条件异常");
        List<OrderItem> list = new ArrayList<>();
        // 每个字段各自排序
        for (int i = 0; i < orderByArr.length; i++) {
            String orderByStr = orderByArr[i];
            String isAscStr = isAscArr.length == 1 ? isAscArr[0] : isAscArr[i];
            if ("asc".equals(isAscStr))
                list.add(OrderItem.asc(orderByStr));
            else if ("desc".equals(isAscStr))
                list.add(OrderItem.desc(orderByStr));
            else
                throw new RuntimeException("【PageEntity】初始化请求分页条件异常");
        }
        return list;
    }

}
